import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter,constantRoutes,allAsyncRoutes,anyRoutes } from '@/router'
import {cloneDeep} from 'lodash'
import router from '@/router'
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    routes: [],
    buttons: [],
    roles: []
  }
}

const state = getDefaultState()

function filterAsyncRoutes(allAsyncRoutes,routesName) {
  let result = allAsyncRoutes.filter(item => {
    if(routesName.indexOf(item.name) !== -1) {
      if(item.children && item.children.length > 0) {
        filterAsyncRoutes(item.children,routesName)
      }
      return true
    }
  })
  return result
}
const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state,userInfo) => {
    state.name = userInfo.name
    state.avatar = userInfo.avatar
  },
  SET_ROUTES: (state,asyncRoutes) => {
    state.routes = constantRoutes.concat(asyncRoutes,anyRoutes)
    router.addRoutes([...asyncRoutes,anyRoutes])
  }
}

const actions = {
  async login({commit,state},loginInfo) {
    const {username,password} = loginInfo
    try {
      let result = await login({username: username.trim(),password})
      commit('SET_TOKEN',result.data.token)
      setToken(result.data.token)
    }catch(error) {
      this.$message.error('登录失败'+error.message)
    }
  },
  async getInfo({commit,state}) {
    try {
      let result = await getInfo(state.token)
      commit('SET_USERINFO',result.data)
      commit('SET_ROUTES',filterAsyncRoutes(cloneDeep(allAsyncRoutes),result.data.routes))
    }catch(error) {
      this.$message.error('获取用户信息失败'+error.message)
    }
  },
  async logout({commit}) {
    try {
      let result = await logout()
      commit('RESET_STATE')
      removeToken()
      resetRouter()
    }catch(error) {
      this.$message.error('用户退出失败'+error.message)
    }
  },
  async resetToken({commit}) {
    commit('RESET_STATE')
    removeToken()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

